import 'package:flutter/cupertino.dart';
import 'package:lottie/lottie.dart';
import 'package:pp_uikit/pp_uikit_constants.dart';
import 'package:pp_uikit/pp_uikit_localizations.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

// typedef ValueBuilder<T> = T Function();

typedef BodyWidgetBuilder = Widget Function(BuildContext context);

class PPRefresh extends StatelessWidget {
  static RefreshIndicator? customHeader;
  static LoadIndicator? customFooter;

  /// 刷新加载包装的内容体
  final Widget body;

  /// 刷新加载状态控制器
  final PPRefreshController controller;

  /// 是否支持下拉刷新
  final bool enableRefresh;

  /// 是否支持上拉加载
  final bool enableLoadMore;

  /// 刷新回调
  final VoidCallback? onRefresh;

  /// 加载更多回调
  final VoidCallback? onLoadMore;

  const PPRefresh({
    Key? key,
    required this.controller,
    required this.body,
    this.enableRefresh = true,
    this.enableLoadMore = true,
    this.onRefresh,
    this.onLoadMore,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    VoidCallback refreshCallback = onRefresh ??
        () => {
              // 默认1s之后重置刷新
              Future.delayed(const Duration(milliseconds: 1000), () {
                controller.refreshCompleted();
              })
            };
    VoidCallback loadMoreCallback = onLoadMore ??
        () => {
              // 默认1s之后结束加载更多
              Future.delayed(const Duration(milliseconds: 1000), () {
                controller.loadMoreComplete();
              })
            };
    return SmartRefresher(
      controller: controller._refreshController,
      enablePullDown: enableRefresh,
      enablePullUp: enableLoadMore,
      header: customHeader,
      footer: customFooter,
      onRefresh: refreshCallback,
      onLoading: loadMoreCallback,
      child: body,
    );
  }
}

mixin PPRefreshMixin {
  PPRefreshController? _refreshController;

  PPRefreshController get refreshController {
    _refreshController ??= PPRefreshController();
    return _refreshController!;
  }
}

/// 刷新状态控制器业务层包装类
class PPRefreshController {
  RefreshController? _rController;

  RefreshController get _refreshController {
    _rController ??= RefreshController(initialRefresh: false);
    return _rController!;
  }

  void completed() {
    _refreshController.refreshCompleted(resetFooterState: true);
    _refreshController.loadComplete();
  }

  void refreshCompleted() {
    _refreshController.refreshCompleted(resetFooterState: true);
  }

  void loadMoreComplete({bool success = true}) {
    success
        ? _refreshController.loadComplete()
        : _refreshController.loadFailed();
  }

  void loadMoreCompleteWithNoData() {
    _refreshController.loadNoData();
  }

  void requestRefresh() {
    _refreshController.requestRefresh();
  }
}

/// 自定义业务下拉刷新头
class PPDefaultHeaderWidget extends StatelessWidget {
  final RefreshStatus? mode;

  const PPDefaultHeaderWidget(this.mode, {super.key});

  @override
  Widget build(BuildContext context) {
    var strings = PPUIKitLocalizations.getLocalizations(context);
    switch (mode) {
      case RefreshStatus.failed:
      case RefreshStatus.idle:
        return _generateRefreshWidget(false, strings.idleRefreshText);
      case RefreshStatus.canRefresh:
        return _generateRefreshWidget(false, strings.canRefreshText);
      case RefreshStatus.refreshing:
        return _generateRefreshWidget(true, strings.refreshingText);
      case RefreshStatus.completed:
        return _generateRefreshWidget(false, strings.refreshCompleteText);
      default:
        // 默认不支持下拉跳转二楼，所以暂不处理跳转二楼等逻辑
        break;
    }
    return Text(strings.loadFailedText);
  }

  /// 生成头部刷新控件视图
  Widget _generateRefreshWidget(bool animate, String stateText) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 0),
      child: Column(
        children: [
          Lottie.asset(
            'images/anime_loading.zip',
            animate: animate,
            width: 45,
            height: 45,
            package: PPUIKitConstant.packageName,
          ),
          Text(
            stateText,
            style: const TextStyle(fontSize: 14.0),
          )
        ],
      ),
    );
  }
}

/// 自定义业务上拉加载更多
class PPDefaultFooterWidget extends StatelessWidget {
  final LoadStatus? mode;

  const PPDefaultFooterWidget(this.mode, {super.key});

  @override
  Widget build(BuildContext context) {
    var strings = PPUIKitLocalizations.of(context)?.currentLocalization ??
        EnLocalizationsString();
    switch (mode) {
      case LoadStatus.failed:
      case LoadStatus.idle:
        return _generateLoadWidget(false, strings.idleLoadingText);
      case LoadStatus.canLoading:
        return _generateLoadWidget(false, strings.canLoadingText);
      case LoadStatus.loading:
        return _generateLoadWidget(true, strings.loading);
      case LoadStatus.noMore:
        return _generateLoadWidget(false, strings.noMoreText);
      default:
        break;
    }
    return Text(strings.loadFailedText);
  }

  /// 生成加载更多footer视图
  Widget _generateLoadWidget(bool showIndicator, String stateText) {
    List<Widget> children = <Widget>[];
    // 是否显示加载中动画
    if (showIndicator) {
      children.add(Container(
        margin: const EdgeInsets.symmetric(vertical: 0, horizontal: 5),
        child: const CupertinoActivityIndicator(radius: 8),
      ));
    }
    // 加载更多状态文案
    children.add(Text(
      stateText,
      style: const TextStyle(fontSize: 14.0),
    ));
    return SizedBox(
      height: 55.0,
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: children,
      ),
    );
  }
}
